package com.um.jdy.app.device.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.app.device.entity.dto.PBPileInfoDTO;
import com.um.jdy.app.device.entity.vo.*;
import com.um.jdy.common.activity.entity.vo.DiscountsAndStationVO;
import com.um.jdy.common.activity.entity.vo.DiscountsVO;
import com.um.jdy.common.activity.entity.vo.StationAvailableCouponsVO;
import com.um.jdy.common.activity.service.CouponsUserService;
import com.um.jdy.common.activity.service.DiscountsStationService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.charge.entity.po.FreeUser;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.service.FreeUserService;
import com.um.jdy.common.charge.service.OrderService;
import com.um.jdy.common.device.code.DeviceCode;
import com.um.jdy.common.device.entity.po.*;
import com.um.jdy.common.device.entity.vo.*;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.*;
import com.um.jdy.common.member.entity.po.MemberUser;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.jdy.common.member.service.WalletService;
import com.um.jdy.common.month.entity.po.CardPackage;
import com.um.jdy.common.month.entity.po.CardUser;
import com.um.jdy.common.month.service.CardPackageService;
import com.um.jdy.common.month.service.CardUserService;
import com.um.jdy.common.platform.entity.po.DepositFree;
import com.um.jdy.common.platform.entity.po.Notification;
import com.um.jdy.common.platform.entity.po.RentSetting;
import com.um.jdy.common.platform.service.DepositFreeService;
import com.um.jdy.common.platform.service.NotificationService;
import com.um.jdy.common.platform.service.RentSettingService;
import com.um.jdy.rpc.enums.DeviceTypeEnum;
import com.um.jdy.rpc.factory.ServiceFactory;
import com.um.springboot.starter.dao.CommonDao;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.utils.IdUtils;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import com.um.springcloud.dubbo.cluster.DeviceKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Title
 * @Description
 * @Author renjunwei
 * @Date 2023/5/22 10:37
 */
@Slf4j
@Service
public class DeviceManager {

    @Autowired
    PileService pileService;

    @Autowired
    GunService gunService;

    @Autowired
    FeeService feeService;

    @Autowired
    FeeEbPriceService feeEbPriceService;

    @Autowired
    FeeEbPowerService feeEbPowerService;

    @Autowired
    FeeEBoxPriceService feeEBoxPriceService;

    @Autowired
    FeeEBoxPowerService feeEBoxPowerService;

    @Autowired
    FeePlaceService feePlaceService;

    @Autowired
    FeePlaceTimeService feePlaceTimeService;

    @Autowired
    FeeEvPriceService feeEvPriceService;

    @Autowired
    FeeEvTimeService  feeEvTimeService;

    @Autowired
    MemberUserService userService;

    @Autowired
    WalletService walletService;

    @Autowired
    StationService stationService;

    @Autowired
    CommonDao dao;

    @Autowired
    FreeUserService freeUserService;

    @Autowired
    RentSettingService rentSettingService;

    @Autowired
    OrderService orderService;

    @Autowired
    FeePbPriceService feePbPriceService;

    @Autowired
    FeeEbTimeService feeEbTimeService;

    @Autowired
    DepositFreeService depositFreeService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    ServiceFactory serviceFactory;

    @Autowired
    NotificationService notificationService;

    @Autowired
    CardUserService cardUserService;

    @Autowired
    CardPackageService cardPackageService;

    @Autowired
    CouponsUserService couponsUserService;

    @Autowired
    DiscountsStationService discountsStationService;

    /**
     * 查询设备详情
     * @param id
     * @return
     */
    public DeviceDetailVO get(String id){
        Pile pile = pileService.getEntity(id);
        if(null == pile){
            throw new ServiceException(DeviceCode.NoDevice);
        }

        DeviceDetailVO data = new DeviceDetailVO();
        switch (DeviceTypeEnum.valueOf(pile.getDeviceType())){
            case EB:
                data.setEb(getByEB(pile));
                break;
            case PB:
                data.setPb(getByPB(pile));
                break;
            case EBox:
                data.setEbox(getByEBox(pile));
                break;
            case EV:
                data.setEv(getByEV(pile));
                break;
        }

        data.setIsOrderEnable(YesOrNo.No.name());
        Notification notification = notificationService.getEntity("com_id", pile.getComId());
        if(null != notification){
            data.setStopTplId(notification.getStopTplId());
            data.setIsOrderEnable(notification.getIsOrderEnable());
        }

        List<StationAvailableCouponsVO> couponsList = couponsUserService.getStationAvailableList(pile.getDeviceStationId(),
                pile.getDeviceType(), userService.get().getMemberUserId());
        List<DiscountsVO> discountsList = discountsStationService.getDiscountsList(pile.getDeviceStationId(),
                pile.getDeviceType());
        data.setCouponsList(couponsList);
        data.setDiscountsList(discountsList);
        return data;
    }

    /**
     * 扫码查查询设备详情
     * @param code
     * @return
     */
    public DeviceDetailVO scan(String code,String gunNo) {

        String codeAndGunNo = code;

        //汽车桩：桩号14位，枪号2位的规则解析
        if(codeAndGunNo.length() == 16) {
            code = StrUtil.subPre(codeAndGunNo,14);
            gunNo = StrUtil.subSuf(codeAndGunNo, 14);
        }

        //汽车桩：桩号10位，枪号1位的规则解析
        if(codeAndGunNo.length() == 11) {
            code = StrUtil.subPre(codeAndGunNo,10);
            gunNo = StrUtil.subSuf(codeAndGunNo, 10);
        }
        // 不包含端口号直接返回
//        Pile pile = pileService.getEntity("code", code);
//        if(null != pile){
//
//            Station station = stationService.getEntity(pile.getDeviceStationId());
//            if(null == station){ // 充电桩未绑定站场即待运营设备
//                throw new ServiceException(DeviceCode.PileNoRunning);
//            }
//
//            if(StringUtil.equals(pile.getDeviceStatus(), DeviceEnum.DeviceStatus.Online.name()) &&
//                    !StringUtil.isEmpty(pile.getProtocol())){
//                queryAllPorts(pile.getProtocol(),pile.getDeviceType(),pile.getImei());
//            }
//            return BeanUtil.toBean(get(pile.getDevicePileId()), DeviceDetailVO.class);
//        }

        // 包含端口号
        Pile pile = pileService.getEntity("code", code);
        if(null == pile){
            throw new ServiceException(DeviceCode.NoDevice);
        }

        Station station = stationService.getEntity(pile.getDeviceStationId());
        if(null == station){ // 充电桩未绑定站场即待运营设备
            throw new ServiceException(DeviceCode.PileNoRunning);
        }

        if(StringUtil.equals(pile.getDeviceStatus(), DeviceEnum.DeviceStatus.Online.name()) &&
            !StringUtil.isEmpty(pile.getProtocol())){
            queryAllPorts(pile.getProtocol(),pile.getDeviceType(),pile.getImei());
        }

        if(StringUtil.equals(DeviceTypeEnum.EV.name(),pile.getDeviceType())){
            if(StringUtil.isEmpty(gunNo) || StringUtil.equals(gunNo,"0")){
                gunNo = "1";
            }
        }


        DeviceDetailVO deviceDetailVO = get(pile.getDevicePileId());
        if(!StringUtil.isEmpty(gunNo) && !StringUtil.equals(gunNo,"0")) {
            String port = gunNo;
            try {
                switch (DeviceTypeEnum.valueOf(pile.getDeviceType())) {
                    case EB:
                        deviceDetailVO.getEb().setGun(deviceDetailVO.getEb().getGuns().stream().filter(item -> item.getPort() == Integer.parseInt(port)).findAny().get());
                        break;
                    case EBox:
                        deviceDetailVO.getEbox().setGun(deviceDetailVO.getEbox().getGuns().stream().filter(item -> item.getPort() == Integer.parseInt(port)).findAny().get());
                        break;
                    case EV:
                        deviceDetailVO.getEv().setGun(deviceDetailVO.getEv().getGuns().stream().filter(item -> item.getPort() == Integer.parseInt(port)).findAny().get());
                        break;
                }
            }catch (Exception ex){

            }
        }

        return deviceDetailVO;
    }

    /**
     * 查询收费方案详情
     * @param deviceFeeId
     * @return
     */
    public FeeDetailVO getFeeDetail(String deviceFeeId){
        Fee fee = feeService.getEntity(deviceFeeId);
        if(null == fee){
            throw new  ServiceException(DeviceCode.NoFee);
        }
        FeeDetailVO feeDetailVO = BeanUtil.toBean(fee, FeeDetailVO.class);

        List<FeeEvTime> timeList = feeEvTimeService.getList(new String[]{"device_fee_id"}, new String[]{deviceFeeId},
                new String[]{"start_time"}, new String[]{"asc"});
        List<FeeEvTimeVO> times = BeanUtil.copyToList(timeList, FeeEvTimeVO.class);

        List<FeeEvPrice> priceList = feeEvPriceService.getList(new String[]{"device_fee_id"}, new String[]{deviceFeeId},
                new String[]{"sort_no"}, new String[]{"asc"});
        List<FeeEvPriceVO> prices = BeanUtil.copyToList(priceList, FeeEvPriceVO.class);

        FeePlace feePlace = feePlaceService.getEntity("device_fee_id",deviceFeeId);
        FeePlaceVO feePlaceVO = BeanUtil.toBean(feePlace, FeePlaceVO.class);

        List<FeePlaceTime> placeTimeList = new ArrayList<>();
        if(YesOrNo.Yes.name().equals(feePlace.getStatus())){
            placeTimeList = feePlaceTimeService.getList(new String[]{"device_fee_id"}, new String[]{deviceFeeId},
                    new String[]{"start_time"}, new String[]{"asc"});
        }
        List<FeePlaceTimeVO> placeTimes = BeanUtil.copyToList(placeTimeList, FeePlaceTimeVO.class);

        feeDetailVO.setTimes(times);
        feeDetailVO.setPrices(prices);
        feeDetailVO.setPlaceTimes(placeTimes);
        feeDetailVO.setPlace(feePlaceVO);
        return feeDetailVO;
    }

    /**
     * 查询不同时间的电费+服务费价格
     * @param feeId
     * @return
     */
    public List<EVFeeTimePriceVO> getPrices(String feeId){
        List<EVFeeTimePriceVO> prices = feeService.getViewModelList("get_ev_fee_time_price_list",EVFeeTimePriceVO.class,new Object[]{feeService.getComId(),feeId});
        return prices;
    }

    /**
     * 查询不同时间的占位费价格
     * @param feeId
     * @return
     */
    public List<FeePlaceTimeVO> getPlacePrices(String feeId){
        List<FeePlaceTime> feePlaceTimes = feePlaceTimeService.getList("device_fee_id",feeId,"start_time","asc");
        return UMBeanUtils.copyBeanList(feePlaceTimes,FeePlaceTimeVO.class);
    }

    /**
     * 校验用户是否站场充电白名单用户,true-白名单，false-非白名单
     * @param userId
     * @return
     */
    public boolean checkFreeUser(String userId, String stationId, String pileId,String comId) {
        List<FreeUser> list = freeUserService.getRows(new String[]{"device_station_id", "member_user_id","com_id"},
                new String[]{stationId, userId,comId});
        return list.stream().anyMatch(item -> pileId.equals(item.getDevicePileId()) || "".equals(StringUtil.getTrim(item.getDevicePileId())));
    }

    /**
     * 校验站场是否免费充电(活动使用-暂不用)
     * @param stationId
     * @return
     */
    public boolean checkFreeStation(String stationId) {
        Map userStation = dao.queryMapBySQLName("get_station_free_activity", new String[]{stationId});
        return userStation != null;
    }

    public EBDeviceDetailVO getByEB(Pile pile){

        Station station = stationService.getEntity(pile.getDeviceStationId());

        List<Gun> gunList = gunService.getList("device_pile_id", pile.getDevicePileId(), "port", "asc");

        List<FeeEbPrice> priceList = feeEbPriceService.getList("device_fee_id", pile.getDeviceFeeId(), "price", "asc");

        List<FeeEbPower> powerList = feeEbPowerService.getList("device_fee_id", pile.getDeviceFeeId(), "price", "asc");

        List<FeeEbTime> timeList = feeEbTimeService.getList("device_fee_id", pile.getDeviceFeeId(), "start_time", "asc");

        Fee fee = feeService.getEntity(pile.getDeviceFeeId());
        if(fee == null){
            throw new ServiceException(DeviceCode.NoFee);
        }

        String uid = userService.get().getMemberUserId();

        boolean isFree = checkFreeUser(uid,pile.getDeviceStationId(),pile.getDevicePileId(),pile.getComId());
        MonthCardVO monthCard = getMonthCard(uid,pile.getDeviceStationId());

        EBDeviceDetailVO data = new EBDeviceDetailVO();
        data.setPile(BeanUtil.toBean(pile, PileVO.class))
                .setGuns(BeanUtil.copyToList(gunList, GunVO.class))
                .setPowers(BeanUtil.copyToList(powerList, FeeEbPowerVO.class))
                .setPrices(BeanUtil.copyToList(priceList, FeeEbPriceVO.class))
                .setTimes(BeanUtil.copyToList(timeList, FeeEbTimeVO.class))
                .setStation(BeanUtil.toBean(station, StationVO.class))
                .setFeeType(fee.getFeeType())
                .setEnergyPrice(fee.getEnergyPrice())
                .setFree(isFree)
                .setMonthCard(monthCard)
                .setBalance(walletService.getBalance(uid,userService.get().getComId()));



        return data;
    }

    public PBDeviceDetailVO getByPB(Pile pile){

        String uid = userService.get().getMemberUserId();

        PBDeviceDetailVO data = new PBDeviceDetailVO();

        PBPileInfoDTO pbPile = pileService.getViewModel("get_pb_device_info", PBPileInfoDTO.class, new Object[]{pile.getCode(),pile.getComId()});
        RentSetting rentSetting = rentSettingService.getEntity("com_id", pile.getComId());
        DepositFree depositFree = depositFreeService.getEntity("com_id",pile.getComId());
        List<Order> orderList = orderService.getList(new String[]{"member_user_id", "status", "device_type"},
                new Object[]{uid, OrderEnum.Status.Charging.name(), DeviceTypeEnum.PB.name()});

        boolean isFree = checkFreeUser(uid,pile.getDeviceStationId(),pile.getDevicePileId(),pile.getComId());

        FeePbPrice fee = feePbPriceService.getEntity("device_fee_id", pile.getDeviceFeeId());
        if(null == fee){
            throw new ServiceException(DeviceCode.NoFee);
        }

        Station station = stationService.getEntity(pile.getDeviceStationId());

        //计费金额(分)
        int price = fee.getPrice();
        //计费时长(秒)
        int duration = fee.getDuration();
        //24小时金额(分)
        int daysAmount = fee.getDaysAmount();
        //封顶金额(分)
        int maxAmount = fee.getMaxAmount();

        String durationPrice = "";
        if(duration < 3600){
            durationPrice = (duration/60) + "分钟";
        }else{
            durationPrice = (duration / 3600) + "小时";
        }

        int shopNum = 0;
        if(StringUtil.getTrim(rentSetting.getShopDisplayType()).equals("number")){
            shopNum = rentSetting.getShopNum();
        }else{
            double longitude = StringUtil.toDouble(station.getLongitude());
            double latitude = StringUtil.toDouble(station.getLatitude());
            shopNum = (int)dao.queryCountBySQLName("get_nearest_station_num",
                    new Object[]{longitude, latitude,userService.getComId(),rentSetting.getDistance()});
        }

        data.setAllowMaxNum(null == rentSetting ? 0 : rentSetting.getMaxOrders());
        data.setOrderNum(orderList.size());
        data.setRentNum(pbPile.getRentNum());
        data.setReturnNum(pbPile.getReturnNum());
        data.setPile(BeanUtil.toBean(pile, PileVO.class));
        data.setFee(BeanUtil.toBean(fee, FeePbPriceVO.class));
        data.setFree(isFree);
        data.setText1(String.format("%s分钟内归还免费",fee.getFreeDuration()/60));
        data.setText2(String.format("%s元/%s", priceFormat(price),durationPrice));
        data.setText3(String.format("%s元/24小时",priceFormat(daysAmount)));
        data.setText4(String.format("封顶%s元",priceFormat(maxAmount)));
        data.setText5(String.format("不足%s按%s收费",durationPrice,durationPrice));
        data.setText6(String.format("所有门店通用通还，附近有%s余家门店",shopNum));

        data.setOpenWxScore(depositFree.getOpenWxScore());
        data.setOpenAlipayScore(depositFree.getOpenAlipayScore());
        return data;

    }


    public EBoxDeviceDetailVO getByEBox(Pile pile) {
        Station station = stationService.getEntity(pile.getDeviceStationId());
        List<Gun> gunList = gunService.getList("device_pile_id", pile.getDevicePileId(), "port", "asc");
        //List<FeeEBoxPrice> priceList = feeEBoxPriceService.getList("device_fee_id", pile.getDeviceFeeId(), "price", "asc");
        List<FeeEBoxPower> powerList = feeEBoxPowerService.getList("device_fee_id", pile.getDeviceFeeId(), "price", "asc");
        FeePlace feePlace = feePlaceService.getEntity("device_fee_id", pile.getDeviceFeeId());

        if(feePlace == null) {
            throw new ServiceException(DeviceCode.NoFee);
        }

        boolean status = StringUtil.getTrim(feePlace.getStatus()).equals("Yes");
        FeePlaceDetailVO feePlaceDetailVo = new FeePlaceDetailVO();

        feePlaceDetailVo.setStatus(status);

        List<String> list = new ArrayList<>();

        Integer fee_duration = feePlace.getFreeDuration();

        if(fee_duration > 0) {
            String text = String.format("前%s分钟免费",fee_duration);
            list.add(text);
        }

        if(feePlace.getPrice() > 0) {
            String text = String.format("%s元/小时",priceFormat(feePlace.getPrice().intValue()));
            list.add(text);

            if(feePlace.getMaxAmount() > 0) {
                text = String.format("每次封顶%s元", priceFormat(feePlace.getMaxAmount().intValue()));
                list.add(text);
            }

        }

        feePlaceDetailVo.setList(list);

        String uid = userService.get().getMemberUserId();

        boolean isFree = checkFreeUser(uid,pile.getDeviceStationId(),pile.getDevicePileId(),pile.getComId());

        EBoxDeviceDetailVO data = new EBoxDeviceDetailVO();
        data.setStation(BeanUtil.toBean(station, StationVO.class));
        data.setGuns(BeanUtil.copyToList(gunList, GunVO.class));
//        data.setPrices(BeanUtil.copyToList(priceList, FeeEBoxPriceVO.class));
        data.setPowers(BeanUtil.copyToList(powerList, FeeEBoxPowerVO.class));
        data.setFree(isFree);
        data.setPlace(BeanUtil.toBean(feePlaceDetailVo, FeePlaceDetailVO.class));
        data.setBalance(walletService.getBalance(uid,userService.get().getComId()));
        data.setPile(BeanUtil.toBean(pile, PileVO.class));

        //TODO 未来也可以加入月卡
        return data;
    }

    public EVDeviceDetailVO getByEV(Pile pile) {
        Station station = stationService.getEntity(pile.getDeviceStationId());
        List<Gun> gunList = gunService.getList("device_pile_id", pile.getDevicePileId(), "port", "asc");



        DateTime now = DateTime.now();
        String value = DateUtil.format(now,"HH:mm");
        EVFeeTimePriceVO currentFeeTimePrice = feeService.getViewModel("get_ev_fee_time_price",EVFeeTimePriceVO.class,
                new Object[]{pile.getComId(),pile.getDeviceFeeId(),value,value});
        List<EVFeeTimePriceVO> prices = feeService.getViewModelList("get_ev_fee_time_price_list",EVFeeTimePriceVO.class,new Object[]{pile.getComId(),pile.getDeviceFeeId()});

        FeePlace feePlace = feePlaceService.getEntity("device_fee_id", pile.getDeviceFeeId());
        List<FeePlaceTime> feePlaceTimes = feePlaceTimeService.getList("device_fee_id",pile.getDeviceFeeId(),"start_time","asc");

        if(feePlace == null) {
            throw new ServiceException(DeviceCode.NoFee);
        }


        FeePlaceTimeVO currentPlaceTimePrice = feeService.getViewModel("get_ev_place_time_price",FeePlaceTimeVO.class,
                new Object[]{pile.getComId(),pile.getDeviceFeeId(),value,value});
        EVPlaceDetailVO evPlaceDetailVo = new EVPlaceDetailVO();
        BeanUtils.copyProperties(feePlace,evPlaceDetailVo);
        evPlaceDetailVo.setPlaceTimes(UMBeanUtils.copyBeanList(feePlaceTimes,FeePlaceTimeVO.class));
        evPlaceDetailVo.setCurrentPlaceTime(currentPlaceTimePrice);

        String uid = userService.get().getMemberUserId();

        boolean isFree = checkFreeUser(uid,pile.getDeviceStationId(),pile.getDevicePileId(),pile.getComId());

        EVDeviceDetailVO data = new EVDeviceDetailVO();
        data.setStation(BeanUtil.toBean(station, StationVO.class));
        data.setGuns(BeanUtil.copyToList(gunList, GunVO.class));
        data.setCurrentPrice(currentFeeTimePrice);
        data.setPrices(prices);
        data.setPlaceDetailVO(evPlaceDetailVo);
        data.setFree(isFree);
        data.setBalance(walletService.getBalance(uid,userService.get().getComId()));
        data.setPile(BeanUtil.toBean(pile, PileVO.class));
        return data;
    }

    /**
     * 查询月卡对象
     * @param userId
     * @param stationId
     * @return
     */
    private MonthCardVO getMonthCard(String userId,String stationId){
        MonthCardVO monthCardVO = new MonthCardVO();

        List<CardPackage> cardPackages = cardPackageService.getList("device_station_id",stationId);
        if(cardPackages.size() <= 0){
            monthCardVO.setIsEnable(YesOrNo.No.name());
            return monthCardVO;
        }

        monthCardVO.setIsEnable(YesOrNo.Yes.name());

        CardUser cardUser = cardUserService.getEntityBySqlName("get_user_station_month_card",cardUserService.getComId(),userId,stationId);
        if(cardUser == null){
            monthCardVO.setRemainDays(0);
        }else{
            int days = (int)DateUtil.between(DateUtil.parseDate(DateUtil.format(new Date(),"yyyy-MM-dd")), cardUser.getEndDate(), DateUnit.DAY);
            monthCardVO.setRemainDays(days);
            monthCardVO.setMaxPower(cardUser.getMaxPower());
            monthCardVO.setPackageId(cardUser.getMonthCardPackageId());
            for(CardPackage item : cardPackages){
                if(item.getMaxPower() > cardUser.getMaxPower()){
                    monthCardVO.setAllowUpgrade(YesOrNo.Yes.name());
                    break;
                }
            }
        }



        return monthCardVO;
    }

    /**
     * 用户是否有月卡
     *
     * @return
     */
    public boolean hasMonthCard(String userId, String stationId) {
        MonthCardVO monthCard = getMonthCard(userId,stationId);
        return monthCard.getRemainDays() > 0;
    }

    /**
     * 查询设备所有端口最新状态
     * @param protocol
     * @param deviceType
     * @param imei
     */
    private void queryAllPorts(String protocol,String deviceType,String imei){

        if(deviceType.equals(DeviceTypeEnum.EB.getKey())){//查询充电端所有端口
            serviceFactory.getRpcEBDeviceService(protocol).reqQueryPorts(IdUtils.getPrimaryKey(), new DeviceKey(imei));
        }else if(deviceType.equals(DeviceTypeEnum.PB.getKey())){//查询充电宝所有端口
            serviceFactory.getRpcPBDeviceService(protocol).reqQueryPort(IdUtils.getPrimaryKey(), new DeviceKey(imei), 255);
        }else if(deviceType.equals(DeviceTypeEnum.EBox.getKey())) {
            serviceFactory.getRpcEBoxDeviceService(protocol).reqQueryPorts(IdUtils.getPrimaryKey(), new DeviceKey(imei));
        }
    }

    /**
     * 格式化金额，如果是正数就不要小数点位
     * @param price
     * @return
     */
    private String priceFormat(int price){
        double n  = NumberUtil.div(price, 100, 2);
        BigDecimal bg = new BigDecimal(n).setScale(2, RoundingMode.UP);
        double num = bg.doubleValue();
        long round = Math.round(num);
        if (round - num == 0) {
            return String.valueOf((long) num);
        }else{
            return NumberUtil.div(price, 100, 2)+"";
        }
    }

    public List<FrequentDeviceItemVO> getFrequentList(){
        MemberUser user = userService.get();
        if(user == null){
            return new ArrayList<>();
        }

        return pileService.getViewModelList("get_frequent_device_list",FrequentDeviceItemVO.class,
                new Object[]{user.getComId(),user.getMemberUserId(),user.getComId(),user.getMemberUserId(),user.getComId()});
    }
}
